package com.hc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hc.common.bean.PageBean;
import com.hc.common.enums.ResultEnum;
import com.hc.constant.GlobalConstant;
import com.hc.domain.User;
import com.hc.ex.GlobalException;
import com.hc.mapper.UserMapper;
import com.hc.query.UserCondition;
import com.hc.res.UserItem;
import com.hc.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 六月Bing
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public int updateBatchSelective(List<User> list) {
        return baseMapper.updateBatchSelective(list);
    }

    @Override
    public int batchInsert(List<User> list) {
        return baseMapper.batchInsert(list);
    }

    @Override
    public PageBean<UserItem> queryByCondition(UserCondition condition) {
        // 用户查询条件为空 抛出参数异常
        if (condition == null) {
            throw new GlobalException(ResultEnum.PARAM_ERROR);
        }
        // 如果分页数据为空，使用默认分页
        final Long current = condition.getCurrent() == null ? 1 : condition.getCurrent();
        final Integer pageSize = condition.getPageSize() == null ? GlobalConstant.PageSize.DEFALUT_PAGE_SIZE : condition.getPageSize();
        IPage<UserItem> page = new Page<>(current,pageSize);
        userMapper.selectList(page,condition);
        return PageBean.init(page);
    }

    /**
     * 判断用户名是否已经存在
     * @param nickname
     * @return
     */
    @Override
    public boolean checkNickname(String nickname) {
        if (!ObjectUtils.isEmpty(nickname)){
            QueryWrapper<User> queryWrapper = new QueryWrapper<User>().eq("nickname",nickname);
            User user = userMapper.selectByNickname(nickname);
            return !ObjectUtils.isEmpty(user);
        }else {
            throw new GlobalException(ResultEnum.PARAM_ERROR);
        }
    }
}